<?php

namespace Beerus\Modules\DecoCompany\Actions;

use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DecoCompanyOrder;
use Doraemon\model\DecoCompanyPayService;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;

class ModifyAuthTime extends RowAction
{
	public $name = '修改认证时间';
	const TOAST_ALERT = '确定修改认证时间吗？';

	public function handle($id, Request $request)
	{
		$params = $request->all();
		$auth_time = strtotime($params['auth_time']);
		$auth_expire_time = $auth_time + 365*24*3600;
		
		$last_order = DecoCompanyOrder::get('*', [
			'uid' => $params['uid'],
			'pay_status' => DecoCompanyOrder::PAY_STATUS_PAID,
			'refund_status' => DecoCompanyOrder::NOT_REFUND,
			'ORDER' => [
				'pay_time' => 'DESC'
			],
		]);

		if (empty($last_order)) {
			return $this->response()->error('用户还未支付')->refresh();
		}

		$create_time = $last_order['create_time'];
		$deadline = $create_time + 60*24*3600;

		if ($auth_time < $create_time || $auth_time > $deadline) {
			return $this->response()->error('不在规定范围，仅支持入住后的60天以内')->refresh();
		}

		$data = [
			'id' => $id,
			'auth_time' => $auth_time,
			'auth_expire_time' => $auth_expire_time,
			'uid' => $params['uid']
		];
		$res = DecoCompanyAuth::action(function () use ($data, $last_order) {
			$res = DecoCompanyAuth::updateInfoById($data['id'], [
				'auth_time' => $data['auth_time'],
				'auth_expire_time' => $data['auth_expire_time']
			]);
			if (!$res) return false;
			$res = DecoCompany::update([
				'auth_time' => $data['auth_time']
			], [
				'uid' => $data['uid']
			]);
			if (!$res) return false;
			$res = DecoCompanyOrder::update([
				'start_date' => date('Y-m-d', $data['auth_time']),
				'end_date' => date('Y-m-d', $data['auth_expire_time'])
			], [
				'id' => $last_order['id']
			]);
			if (!$res) return false;
			// 同步服务记录时间
            $res = DecoCompanyPayService::updateInfo([
                'start_time' => $data['auth_time'],
                'end_time' => $data['auth_expire_time'],
            ],[
                'dsn' => $last_order['dsn'],
            ]);
            if (!$res) return false;

			return true;
		});

		if ($res) {
			return $this->response()->success('操作成功(＾－＾)V')->refresh();
		}else{
			return $this->response()->success('操作失败,请稍后重试o(TωT)o');
		}
	}

	public function retrieveModel(Request $request)
	{
		if (!$key = $request->get('_key')) {
			return false;
		}
		return $key;
	}

	public function form($request)
	{
		$uid = $request->uid;
		$auth_info = DecoCompanyAuth::getByUid($uid);
		$auth_time = date('Y-m-d', $auth_info['auth_time']);
		$auth_expire_time = date('Y-m-d', $auth_info['auth_expire_time']);
		$this->date('auth_time', '认证生效时间')->default($auth_time)->required('不能为空');
		$this->date('auth_expire_time', '认证到期时间')
			->readonly()->default($auth_expire_time);
		$this->hidden('uid', '用户uid')->default($uid);

		$this->confirm(self::TOAST_ALERT);
	}
}
